package com.app.reptile.tasks;

import com.app.reptile.base.AppConfig;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.Set;

/**
 * Selenium 爬虫工具
 */
public abstract class AbstractDriverTask extends AbstractTask {

    protected abstract void start(ChromeDriver chromeDriver) throws Exception;

    @Override
    protected void start() throws Exception {

        String path = System.getProperty("webdriver.chrome.driver");
        if (StringUtils.isBlank(path)){
            System.setProperty("webdriver.chrome.driver", AppConfig.CONFIG.getProperty("webdriver.chrome.driver"));
        }
        ChromeOptions chromeOptions = new ChromeOptions();
        ChromeDriver chromeDriver = new ChromeDriver(chromeOptions);
        try{
            start(chromeDriver);
        }catch (Exception e){
            logger.error("系统错误",e);
        }finally {
            String handle = chromeDriver.getWindowHandle();
            Set<String> hands = chromeDriver.getWindowHandles();
            for(String hand : hands){
                if (!hand.equals(handle)){
                    //进行窗口切换 先关闭非当前窗口
                    chromeDriver.switchTo().window(hand);
                    chromeDriver.close();
                }
            }
            chromeDriver.switchTo().window(handle);
            chromeDriver.close();//关闭全部窗口
            chromeDriver.quit();//正常还需要调用次函数 关闭了全部chromeDriver也会消失
        }
    }

}
